package cn.shadow.controller;

import cn.shadow.mines.Mines;
import cn.shadow.mines.MinesData;
import cn.shadow.mines.MinesPoint;
import cn.shadow.service.MinesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@ResponseBody
@RequestMapping("/mines")
public class MinesController extends BaseController {
    @Autowired
    private MinesService service;

    @GetMapping("/mines_init")
    public String minesInit(@RequestParam("row") Integer row,
                            @RequestParam("col") Integer col,
                            @RequestParam("num") Integer num) {
        HttpSession session = request.getSession();
        Object minus = session.getAttribute("mines");
        if (minus != null) {
            Mines m = (Mines) minus;
            if (m.getCol() == col && m.getRow() == row && m.getMinus() == num) {
                m.reset();
            } else {
                m = service.getInitMinus(row, col, num);
                session.setAttribute("mines", m);
            }
        } else {
            Mines m = service.getInitMinus(row, col, num);
            session.setAttribute("mines", m);
        }
        return "success";
    }

    @GetMapping("/mines_click")
    public MinesData minesClick(@RequestParam("row") Integer row, @RequestParam("col") Integer col) {
        HttpSession session = request.getSession();
        Object minus = session.getAttribute("mines");
        if (minus != null) {
            Mines m = (Mines) minus;
            return service.minusClick(m, row, col);
        }
        return null;
    }

    /**
     * 插旗子
     */
    @GetMapping("/mines_flag")
    public MinesPoint minesFlagged(@RequestParam("row") Integer row, @RequestParam("col") Integer col) {
        HttpSession session = request.getSession();
        Object minus = session.getAttribute("mines");
        Mines m = (Mines) minus;
        return service.flagged(m, row, col);
    }
}
